﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Lion.WeiXin.Core.Message
{
    /// <summary>
    /// 有msgid的消息推荐使用msgid排重。事件类型消息推荐使用FromUserName + CreateTime 排重。
    /// </summary>
   public class MsgModel
    {
       public MsgModel() {
           // 默认是文本类型
           this.MsgType = MessageType.text.ToString();
       }

       /// <summary>
       /// 初始化消息
       /// </summary>
       /// <param name="message"></param>
       public MsgModel(string message)
       {
           XDocument doc = XDocument.Parse(message);
           this.ToUserName = doc.Root.Element("ToUserName").Value;
           this.FromUserName = doc.Root.Element("FromUserName").Value;
           this.CreateTime =long.Parse(doc.Root.Element("CreateTime").Value);
           this.MsgType = doc.Root.Element("MsgType").Value;
           this.ContentXML = doc.Root.Element("Content").Value;
           if (!string.IsNullOrEmpty(doc.Root.Element("MsgId").Value))
           {
               this.MsgId =long.Parse(doc.Root.Element("MsgId").Value);
           }          
           
       }

       /// <summary>
        /// 接收方帐号（收到的OpenID）
       /// </summary>
       public string ToUserName { get; set; }
       /// <summary>
       /// 开发者微信号
       /// </summary>
       public string FromUserName { get; set; }
       /// <summary>
       /// 消息创建时间 （整型）
       /// </summary>
       public long CreateTime { get; set; }
       /// <summary>
       /// 消息类型
       /// </summary>
       public string MsgType { get; set; }

       /// <summary>
       /// 消息内容
       /// </summary>
       public string ContentXML { get; set; }
       /// <summary>
       /// 消息ID
       /// </summary>
       public long MsgId { get; set; }
     

       public DateTime ConvertIntToDate(long totalSeconds)
       {
           System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
           return startTime.AddSeconds(totalSeconds);
       }

       /// <summary>
       /// 返回时间整数，起始时间为1970-1-1 00:00:00:0000
       /// </summary>
       /// <param name="time"></param>
       /// <returns></returns>
       public long ConvertDateToInt(System.DateTime time)
       {
           System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
           return (long)(time - startTime).TotalSeconds;
       }

       //private DateTime UnixTimeToTime(string timeStamp)
       //{
       //    DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
       //    long lTime = long.Parse(timeStamp + "0000000");
       //    TimeSpan toNow = new TimeSpan(lTime);
       //    return dtStart.Add(toNow);
       //}
    }
}
